import { Modal, Button, Progress, message } from 'antd';
import { BuildGraphStatus } from 'types/graph-builder';
import { useEffect, useState } from 'react';
import { graphBuilderApi } from 'services';

import { renderStatusTag } from '../../helper';
import styles from './index.module.css';

interface BuildProgressModalProps {
  open: boolean;
  graphId: string;
  onClose: () => void;
}

const BuildProgressModal = ({
  open,
  graphId,
  onClose,
}: BuildProgressModalProps) => {
  const [pollTimer, setPollTimer] = useState<NodeJS.Timeout | null>(null);
  const [buildingStatus, setBuildingStatus] =
    useState<BuildGraphStatus>('pending');
  const [buildAlready, setBuildAlready] = useState<number>(0);
  const [buildTotal, setBuildTotal] = useState<number>(0);
  const [percent, setPercent] = useState<number>(0);

  // 在弹框关闭时重置状态
  useEffect(() => {
    if (!open) {
      setBuildingStatus('pending');
      setBuildAlready(0);
      setBuildTotal(0);
      setPercent(0);
      stopPolling();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  // 停止轮询的方法
  const stopPolling = () => {
    if (pollTimer) {
      clearTimeout(pollTimer);
      setPollTimer(null);
    }
  };

  // 在组件卸载时清理定时器
  useEffect(() => {
    return () => {
      stopPolling();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (open) {
      fetchBuildProgress();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  // 获取构建进度
  const fetchBuildProgress = async () => {
    try {
      const res = await graphBuilderApi.getBuildProgress(graphId);
      if (res.code === 200) {
        setBuildingStatus(res.data.status);
        setBuildTotal(res.data.build_total);
        setBuildAlready(res.data.already_build);
        setPercent(
          Math.floor((res.data.already_build / res.data.build_total) * 100)
        );

        // 如果构建进度弹窗已打开，且构建状态不为完成或失败，则继续轮询
        if (res.data.status !== 'completed' && res.data.status !== 'failed') {
          const timer = setTimeout(() => {
            fetchBuildProgress();
          }, 5000);

          setPollTimer(timer);
        }

        // 如果构建进度弹窗已打开，且构建状态为完成或失败，则停止轮询
        if (res.data.status === 'completed' || res.data.status === 'failed') {
          stopPolling();
        }
      } else {
        message.error('获取构建进度失败');
        stopPolling();
      }
    } catch (error) {
      message.error('获取构建进度失败');
      stopPolling();
    }
  };

  return (
    <Modal
      title="图谱构建进度"
      open={open}
      footer={
        <Button type="primary" onClick={onClose}>
          知道了
        </Button>
      }
      onCancel={onClose}
      maskClosable={false} // 防止误点击蒙层关闭
      style={{ zIndex: 1001 }} // 确保比新建图谱弹框的层级高
    >
      <div className={styles.buildProgress}>
        <Progress
          percent={percent}
          status="active"
          strokeColor={{
            '0%': '#108ee9',
            '100%': '#87d068',
          }}
          strokeWidth={8}
        />
        <div className={styles.buildStatus}>
          <div className={styles.statusText}>
            构建状态：{renderStatusTag(buildingStatus)}
            {buildingStatus === 'completed' && (
              <span className={styles.successIcon}>✓</span>
            )}
          </div>
          <div className={styles.progressDetail}>
            已处理数据：{buildAlready} / {buildTotal}
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default BuildProgressModal;
